
import os
import pandas as pd
from scipy.spatial import cKDTree
from collections import Counter
import math
from imputation.reading import read_all_csv_in_folder  # 确保你有这个模块和函数
m=8
cogindex=4
lonindex=1
latindex=2
def nextpoint(a, data,  reference_point,dlon,dlat,threshold_distance,threshold_angle,current_depth,visited_points):
    points = list(zip(data.iloc[:, lonindex], data.iloc[:, latindex]))
    tree = cKDTree(points)
    query_point = (a[0], a[1])
    indices_within_threshold = tree.query_ball_point(query_point, threshold_distance/2)
    COG = [data.iloc[i,cogindex ] for i in indices_within_threshold]
    intervals = [(i * 360/m, (i + 1) * 360/m) for i in range(m)]
    def get_interval(value):
        for i, (start, end) in enumerate(intervals):
            if start <= value < end:
                return i
        if value == 360:
            return 7
        return 7# 或者选择其他默认值

    interval_distribution = Counter(get_interval(value) for value in COG if get_interval(value) is not None)
    total_points = len(COG)

    interval_frequency = {interval: count / total_points for interval, count in interval_distribution.items()}
    # significant_intervals = [interval for interval, frequency in interval_frequency.items() if frequency > threshold_angle]
    # 找到频率最大的间隔
    centers = []
    dlon = float(dlon)
    dlat = float(dlat)
    # print(dlon,dlat)
    linepoint=(a[0]+dlon,a[1]+dlat)
    if tree.query_ball_point(linepoint, threshold_distance/2):
        # centers.append(linepoint)
        # 查询最近的点
        distance, index = tree.query(linepoint, k=1)
        closest_point = (data.iloc[index, lonindex], data.iloc[index, latindex])
        centers.append(closest_point)

    significant_intervals=[]
    if  interval_frequency:
        most_frequent_interval = max(interval_frequency, key=interval_frequency.get)
        another_interval =most_frequent_interval-4 if most_frequent_interval-4>=0 else most_frequent_interval+4
        significant_intervals = [most_frequent_interval,another_interval]
        # print(significant_intervals)
    for interval in significant_intervals:
        points_in_interval = [(data.iloc[i, lonindex], data.iloc[i, latindex]) for i in indices_within_threshold if
                              get_interval(data.iloc[i, cogindex]) == interval]
        unvisited_points = [point for point in points_in_interval if point not in visited_points]
        if unvisited_points:
            angle = interval * 360 / m + m / 2
            avg_lat = sum(p[0] for p in unvisited_points) / len(unvisited_points)
            avg_lon = sum(p[1] for p in unvisited_points) / len(unvisited_points)
            centers.append((avg_lat+math.cos(math.radians(angle)) * threshold_distance, avg_lon+math.sin(math.radians(angle)) * threshold_distance))
            visited_points.update(unvisited_points)

        # angle=interval*360/m+m/2
        # new_lat = a[1] + math.cos(math.radians(angle)) * threshold_distance
        # new_lon = a[0] + math.sin(math.radians(angle)) * threshold_distance
        # new_point = ( new_lon,new_lat,)
        # distance, index = tree.query(new_point, k=1)
        # points_in_interval =(data.iloc[index, lonindex], data.iloc[index, latindex])


        # centers.append(points_in_interval)
        # centers.append(new_point)

    if centers:
        # print(centers)
        return centers
    else:
        # print("0")

        return []

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, child_node):
        self.children.append(child_node)
        return child_node

def calculate_distance(point1, point2):
    return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)


def generate_tree(root, data, generate_children, reference_point, threshold_distance, threshold_angle, dlon, dlat,
                  max_depth,  current_depth=0, visited_points=None):
    if visited_points is None:
        visited_points = set()

    # print(f"Current Depth: {current_depth}, Max Depth: {max_depth}")
    if current_depth > max_depth:
        # print("Exceeded max depth, returning None")
        return []

    children = generate_children(root.value, data, reference_point, dlon, dlat, threshold_distance, threshold_angle,
                                 current_depth, visited_points)
    # print(f"Children: {children}")
    if children:
        for child_value in children:
            # print(f"Processing child_value: {child_value}")
            if len(child_value) < 2:
                # print(f"Skipping child_value: {child_value} (length < 2)")
                continue
            child_node = TreeNode(child_value)
            root.add_child(child_node)
            distance = calculate_distance((child_value[0], child_value[1]), reference_point)
            # print(f"Distance from {child_value} to reference_point: {distance}")

            if distance < threshold_distance:
                # print(f"Distance within threshold, returning path: {[root.value] + [child_value]}")
                return [root.value] + [child_value]

            else:
                recursive_path = generate_tree(child_node, data, generate_children, reference_point, threshold_distance,
                                               threshold_angle, dlon, dlat, max_depth, current_depth + 1,
                                               visited_points)
                if recursive_path:
                    # print(f"Found recursive path: {[root.value] + recursive_path}")
                    return [root.value] + recursive_path

    # print("No valid path found, returning None")
    return []

